package com.czxy.service;

import com.czxy.dao.CustomerMapper;
import com.czxy.domain.Customer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{
    @Resource
    private CustomerMapper customerMapper;

    @Override
    public List<Customer> findAll() {
        return customerMapper.findAll();
    }

    @Override
    public void insert(Customer customer) {
        customerMapper.insert(customer);
    }

    @Override
    public void delete(Customer customer) {
        customerMapper.deleteByPrimaryKey(customer);
    }

    @Override
    public Customer findById(Customer customer) {
        return customerMapper.selectByPrimaryKey(customer);
    }

    @Override
    public boolean update(Customer customer) {

        // 检查用户名是否重复了
        // 判断 数据库中如果有名字跟当前名字一样并且id值不一样的数据存在 就代表名字改重复.
        Example example = new Example(Customer.class);
        Example.Criteria ct= example.createCriteria();
        //名字相同
        ct.andEqualTo("custName",customer.getCustName());
        // id值不相同
        ct.andNotEqualTo("custId",customer.getCustId());
        //查询
        List<Customer> list = customerMapper.selectByExample(example);
        if(list.size()>0){
            // 名字改成别的客户名了, 更新失败
            return false;
        }

        // 更新
        customerMapper.updateByPrimaryKeySelective(customer);

        return true;
    }
}
